//2025.8.22青浦演示视觉
#include <rclcpp/rclcpp.hpp>
#include <moveit/move_group_interface/move_group_interface.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <geometry_msgs/msg/twist_stamped.hpp>
#include <tf2/LinearMath/Quaternion.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.hpp>
#include <atomic>
#include <thread>
#include <rclcpp/executors/multi_threaded_executor.hpp>
// #include "servo_visual/doc/examples/realtime_servo/src/visual_control.hpp"   // 修改：包含新创建的头文件
#include "/home/jetson/zc6/src/servo_visual/include/servo_visual/ibvs_control.hpp"
#include <std_msgs/msg/float64.hpp>
#include <algorithm>
#include <vector>
using servo_visual::IBVSControl; 
class CombinedNode : public rclcpp::Node {
public:
    CombinedNode() : Node("combined_node"), force_sign(true), closest_index(0) {
        // 初始化力数据订阅
        force_sub_ = this->create_subscription<geometry_msgs::msg::TwistStamped>(
            "/force_data", 10,
            std::bind(&CombinedNode::force_callback, this, std::placeholders::_1));

        // 初始化MoveGroupInterface
        move_group_ = std::make_shared<moveit::planning_interface::MoveGroupInterface>(
            std::shared_ptr<rclcpp::Node>(this),  // 显式创建shared_ptr
            "zc4");
        
        RCLCPP_INFO(get_logger(), "节点初始化完成");
    }

    // 新增：获取 ibvs_control_node 成员的 getter
    std::shared_ptr<servo_visual::IBVSControl> get_ibvs_control_node() {
        return ibvs_control_node;
    }

    // 修改 start_execution 以接受路径索引
    void start_execution(int path_index) {
        std::thread([this, path_index]() {
            switch (path_index) {
                case 1:
                    executeCartesianPath1();
                    // 创建并初始化 IBVSControl 节点，启动 control_loop 定时器
                    ibvs_control_node = std::make_shared<IBVSControl>();
                    ibvs_control_node->initialize();
                    // 等待 IBVS 执行完毕
                    while(rclcpp::ok() && !ibvs_control_node->isFinished()){
                        RCLCPP_INFO(get_logger(), "IBVS 执行中...");
                        std::this_thread::sleep_for(std::chrono::milliseconds(100));
                    }
                    RCLCPP_INFO(get_logger(), "IBVS 执行完毕，开始返回 middle 位置");
                    std::this_thread::sleep_for(std::chrono::milliseconds(4000));
                    if (returnToMiddle()) {
                        RCLCPP_INFO(get_logger(), "成功返回 middle 位置");
                    } else {
                        RCLCPP_ERROR(get_logger(), "返回 middle 位置失败");
                    }
                    rclcpp::shutdown(); 
                    break;
                default:
                    RCLCPP_ERROR(get_logger(), "无效的路径索引: %d", path_index);
                    break;
            }
        }).detach();
    }

private:
    std::shared_ptr<moveit::planning_interface::MoveGroupInterface> move_group_;
    rclcpp::Subscription<geometry_msgs::msg::TwistStamped>::SharedPtr force_sub_;
    std::atomic<bool> force_sign;
    std::atomic<size_t> closest_index;
    // 新增成员：声明 visual_control_node
    std::shared_ptr<servo_visual::IBVSControl> ibvs_control_node;

    void force_callback(const geometry_msgs::msg::TwistStamped::SharedPtr msg) {
        if (std::abs(msg->twist.linear.z) >= 1.5) {
            force_sign = false;
        } else {
            force_sign = true;
        }
    }

    bool returnToMiddle() {
        // 等待500ms, 确保MoveGroup action client/server已就绪
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        move_group_->setNamedTarget("middle");
        moveit::planning_interface::MoveGroupInterface::Plan home_plan;
        bool success = (move_group_->plan(home_plan) == moveit::core::MoveItErrorCode::SUCCESS);
        if (success) {
            move_group_->execute(home_plan);
            RCLCPP_INFO(get_logger(), "回到middle位置");
            return true;
        }
        RCLCPP_ERROR(get_logger(), "回到middle位置失败");
        return false;
    }

    bool continueCartesianPath(const std::vector<geometry_msgs::msg::Pose>& original_waypoints) {
        geometry_msgs::msg::Pose current_pose = move_group_->getCurrentPose().pose;
        std::vector<geometry_msgs::msg::Pose> remaining_waypoints;
        double min_distance = std::numeric_limits<double>::max();

        for (size_t i = 0; i < original_waypoints.size(); ++i) {
            double dx = current_pose.position.x - original_waypoints[i].position.x;
            double dy = current_pose.position.y - original_waypoints[i].position.y;
            double dz = current_pose.position.z - original_waypoints[i].position.z;
            double distance = std::sqrt(dx*dx + dy*dy + dz*dz);
            if (distance < min_distance) {
                min_distance = distance;
                closest_index = i;
            }
        }

        for (size_t i = closest_index + 1; i < original_waypoints.size(); ++i) {
            remaining_waypoints.push_back(original_waypoints[i]);
        }

        if (remaining_waypoints.empty()) return false;

        move_group_->setStartStateToCurrentState();
        moveit::planning_interface::MoveGroupInterface::Plan new_plan;
        double fraction = move_group_->computeCartesianPath(remaining_waypoints, 0.01, 0.0, new_plan.trajectory_);
        
        if (fraction >= 0.9) {
            move_group_->asyncExecute(new_plan);
            return true;
        }
        return false;
    }

    void executeCartesianPath1() {
        if (!returnToMiddle()) return;
        /* #region  */
        std::vector<geometry_msgs::msg::Pose> waypoints;
        // 目标点1 0/-50/90/15/0
        geometry_msgs::msg::Pose pose1;
        pose1.position.x = -0.011801240508450508;
        pose1.position.y = -1.6717636845861036e-05;
        pose1.position.z = 0.14428133950504773;
        pose1.orientation.x = -2.3927732160852933e-06;
        pose1.orientation.y = 0.3826546744537482;
        pose1.orientation.z = -5.627848297886214e-05;
        pose1.orientation.w = 0.9238914421866365;
        waypoints.push_back(pose1);

        // 目标点2 0/-60/100/10/0
        geometry_msgs::msg::Pose pose2;
        pose2.position.x = -0.022079;
        pose2.position.y = -7.74576e-05;
        pose2.position.z = 0.0950052;
        pose2.orientation.x = -6.4903e-05;
        pose2.orientation.y = 0.422351;
        pose2.orientation.z = -0.000237108;
        pose2.orientation.w = 0.906432;
        waypoints.push_back(pose2);

        // 目标点3 0/-65/110/0/0
        geometry_msgs::msg::Pose pose3;
        pose3.position.x = -0.0021559;
        pose3.position.y = -8.5636e-05;
        pose3.position.z = 0.087629;
        pose3.orientation.x = -1.2533e-05;
        pose3.orientation.y = 0.3815;
        pose3.orientation.z = -0.00027885;
        pose3.orientation.w = 0.92437;
        waypoints.push_back(pose3);

        // 目标点4 0/-70/119/-9/0
        geometry_msgs::msg::Pose pose4;
        pose4.position.x = 0.0151664;
        pose4.position.y = -9.93429e-05;
        pose4.position.z = 0.0808511;
        pose4.orientation.x = -4.666e-06;
        pose4.orientation.y = 0.344447;
        pose4.orientation.z = -0.000031351;
        pose4.orientation.w = 0.9388;
        waypoints.push_back(pose4);

        // 目标点5 0/-78/134/-28/0 
        geometry_msgs::msg::Pose pose5;
        pose5.position.x = 0.051718;
        pose5.position.y = -5.9906e-05;
        pose5.position.z = 0.084033;
        pose5.orientation.x = -0.00040868;
        pose5.orientation.y = 0.24246;
        pose5.orientation.z = -0.00023144;
        pose5.orientation.w = 0.97016;
        waypoints.push_back(pose5);

        // 目标点6 0/-78/138/-44/0
        geometry_msgs::msg::Pose pose6;
        pose6.position.x = 0.086392;
        pose6.position.y = 0;
        pose6.position.z = 0.14227;
        pose6.orientation.x = -0.00011136;
        pose6.orientation.y = 0.065582;
        pose6.orientation.z = -0.00032853;
        pose6.orientation.w = 0.99785;
        waypoints.push_back(pose6);

        // 目标点7 0/-82/142/-52/0 半举平
        geometry_msgs::msg::Pose pose7;
        pose7.position.x = 0.093833;
        pose7.position.y = 0;
        pose7.position.z = 0.15401;
        pose7.orientation.x = -5.9707e-05;
        pose7.orientation.y = 0.039548;
        pose7.orientation.z = -0.00001562;
        pose7.orientation.w = 0.99922;
        waypoints.push_back(pose7);

        // 目标点8 0/-82/145/-60/0 举平
        geometry_msgs::msg::Pose pose8;
        pose8.position.x = 0.093833;
        pose8.position.y = 0;
        pose8.position.z = 0.15401;
        pose8.orientation.x = -5.9707e-05;
        pose8.orientation.y = 0.039548;
        pose8.orientation.z = -0.00001562;
        pose8.orientation.w = 0.99922;
        waypoints.push_back(pose8);

        // 目标点8 0/-90/142/-50/0 刮板
        geometry_msgs::msg::Pose pose9;
        pose9.position.x = 0.077103;
        pose9.position.y = 0;
        pose9.position.z = 0.16429;
        pose9.orientation.x = -4.1935e-05;
        pose9.orientation.y = 0.0093845;
        pose9.orientation.z = -0.0011772;
        pose9.orientation.w = 0.99996;
        waypoints.push_back(pose9);

        //第10个目标位姿 14/-90/142/-50/0 左移
        geometry_msgs::msg::Pose pose10;
        pose10.position.x = 0.071307;
        pose10.position.y = 0.047553;
        pose10.position.z = 0.16428;
        pose10.orientation.x = -0.0011452;
        pose10.orientation.y = 0.0093179;
        pose10.orientation.z = 0.12094;
        pose10.orientation.w = 0.99262;
        waypoints.push_back(pose10);

        //第11个目标位姿 visul位置
        //第11个目标位姿 0/-60/120/-60/0 low-middle
        geometry_msgs::msg::Pose pose11;
        pose11.position.x = 0.11027;
        pose11.position.y = 0;
        pose11.position.z = 0.226;
        pose11.orientation.x = 0;
        pose11.orientation.y = 0;
        pose11.orientation.z = 0;
        pose11.orientation.w = 1;
        waypoints.push_back(pose11);

    /* #endregion */

        move_group_->stop();
        move_group_->setStartStateToCurrentState();
        moveit::planning_interface::MoveGroupInterface::Plan cartesian_plan;
        double fraction = move_group_->computeCartesianPath(waypoints, 0.01, 0.0, cartesian_plan.trajectory_);
        
        if (fraction < 0.9) {
            RCLCPP_ERROR(get_logger(), "初始路径规划失败，完成度: %f", fraction);
            return;
        }

        RCLCPP_INFO(get_logger(), "初始路径规划成功，开始执行...");
        move_group_->asyncExecute(cartesian_plan);
        bool is_stopped = false;
        bool is_forced = false;
        std::atomic<bool> motion_complete(false);
        auto start_time = std::chrono::steady_clock::now();
        const std::chrono::seconds timeout(16); // 设置15秒超时

        while (rclcpp::ok() && !motion_complete && !is_forced) {
            auto elapsed_time = std::chrono::steady_clock::now() - start_time;
            if (elapsed_time > timeout) {
                RCLCPP_ERROR(get_logger(), "运动执行超时");
                motion_complete = true;
                break;
            }
            if (!force_sign.load()) {
                if (!is_stopped) {
                    std::this_thread::sleep_for(std::chrono::seconds(1));
                    RCLCPP_INFO(get_logger(), "检测到过大力，尝试停止运动...");
                    move_group_->stop();
                    is_stopped = true;
                    RCLCPP_INFO(get_logger(), "运动已停止");
                }
            } else {
                if (is_stopped) {
                    std::this_thread::sleep_for(std::chrono::seconds(1));
                    RCLCPP_INFO(get_logger(), "力信号恢复，尝试继续运动...");
                    if (continueCartesianPath(waypoints)) {
                        RCLCPP_INFO(get_logger(), "已恢复运动");
                        is_stopped = false;
                    } else {
                        RCLCPP_INFO(get_logger(), "无法继续运动或路径已完成");
                        motion_complete = true;
                        break;
                    }
                }
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(50));
        }

        if (motion_complete.load()) {
            RCLCPP_INFO(get_logger(), "运动执行循环结束（可能已完成或无法继续）");
        } else if (!rclcpp::ok()) {
            RCLCPP_INFO(get_logger(), "运动执行循环因 rclcpp 关闭而结束");
        }
        move_group_->stop();
    }

};

int main(int argc, char** argv) {
    rclcpp::init(argc, argv);
    auto node = std::make_shared<CombinedNode>();

    rclcpp::executors::MultiThreadedExecutor executor;
    executor.add_node(node);
    
    node->start_execution(1); 

    // 等待 IBVSControl 节点创建成功
    while (rclcpp::ok() && node->get_ibvs_control_node() == nullptr) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
    executor.add_node(node->get_ibvs_control_node());

    RCLCPP_INFO(node->get_logger(), "开始执行器 spin");
    executor.spin();

    RCLCPP_INFO(node->get_logger(), "执行器 spin 结束");
    rclcpp::shutdown();
    return 0;
}